#!/bin/bash

# This script is intended to run, locally, the tests we run at circleci,
# precisely as they are run there.
#
# to do so, it:
# o creates a directory to store local artifacts retrieved from docker
#   see TMP= below
# o runs a the standard test container to retrieve a the qemu, kernel, and bios image
# o runs go test with a default set of tests (./...)
#
# NOTE: if you want more complex behavior, don't make this script more
# complex. Convert it to Go. Complex shell scripts suck.

set -e
set -x

# These docker artifacts should not persist. Place them in tmp.
# tmp is in .gitignore
# I would prefer /tmp/$$.
# Docker really doesn't like this for some reason, even when
# I map it to /out inside the container.
# TMP=/tmp/$$
TMP=`pwd`/tmp
mkdir -p $TMP
chmod 777 $TMP

# The default value is AMD64, but you can override it, e.g.
# UROOT_TESTARCH=arm64 bash RUNLOCAL
export ${UROOT_TESTARCH:=amd64}

case $UROOT_TESTARCH in

  "amd64")
    export UROOT_QEMU="qemu-system-x86_64"
    export UROOT_QEMU_OPTS="-L $TMP/pc-bios -m 1G"
    export UROOT_KERNEL=bzImage
    export UROOT_BIOS=pc-bios
    ;;

  "arm64")
    export UROOT_QEMU=qemu-system-aarch64
    export UROOT_KERNEL=Image
    export UROOT_BIOS=""
    export UROOT_QEMU_OPTS=""
    ;;

  *)
    echo "$UROOT_TESTARCH is not a supported architecture"
    exit 1
    ;;

esac

# We no longer allow you to pick a kernel to run.
# Since we wish to exactly mirror what circleci does, we always use the
# kernel and qemu in the container.
# Note the docker pull only hurts a lot the first time.
# After you have run it once, further cp operations take a second or so.
# By doing it this way, we always use the latest Docker files.
DOCKER=uroottest/test-image-${UROOT_TESTARCH}

docker run -v $TMP:/out $DOCKER cp -a $UROOT_KERNEL  $UROOT_BIOS $UROOT_QEMU /out

ls -l $TMP

# now adjust paths and such
UROOT_KERNEL=$TMP/$UROOT_KERNEL
UROOT_QEMU="$TMP/$UROOT_QEMU $UROOT_QEMU_OPTS"
UROOT_BIOS=$TMP/$UROOT_BIOS

go test "$@" ./...
